<template>
  <div class="app-container">
    <div class="Header">
      <edit-form ref="filterContainer" v-show="showSearch" :editFormMap="filterMap" :editFormData="queryParams">
        <template slot="buttonGroup">
          <el-col :span="4">
            <el-form-item class="buttonGroup">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </template>
      </edit-form>
      <handle-button-group
        :showSearch.sync="showSearch"
        :single="single"
        :multiple="multiple"
        :authModule="{ module: 'question', name: 'bd' }"
        @handleAdd="handleAdd"
        @handleUpdate="handleUpdate"
        @handleDelete="handleDelete"
        @handleExport="handleExport"
        @getList="getList"
      />
    </div>
    <table-list
      ref="tableListContainer"
      :tableListMap="tableMap"
      :request="{
        apiKey: 'BdQuestList',
        params: queryParams,
        method: 'get',
      }"
      @selection-change="handleSelectionChange"
      @changeTableListAction="
        (TableList) => {
          userList = TableList;
        }
      "
    >
      <template slot="hasSelect">
        <el-table-column type="selection" width="55" :align="'center'" />
      </template>
      <template slot="hasHandle">
        <el-table-column label="操作" :align="'center'">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['question:bd:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['question:bd:remove']">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </table-list>
    <!-- 添加或修改必答题对话框 -->
    <el-dialog :title="title" :visible.sync="open" top="0vh" width="1200px" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
      <!-- 基础题目 -->
      <basicQuest
        ref="basicQuest"
        :basicForm="basicForm"
        :basicFormData.sync="params.basicForm"
        :questionDirect="questionDirect"
        :basicQuestionDirect.sync="params.questionDirect"
        type="bd"
      ></basicQuest>
      <!-- 答题选项 -->
      <answerOption ref="answerOption" :optionList="optionList" :answerOptionList.sync="params.optionList" type="bd" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import basicQuest from '../components/basicQuest';
import answerOption from '../components/answerOption';
import { addBd, updateBd, delBd, exportBd, getBd } from '@/api/question/bd';
import { getDataSource } from '@/static/js/dataSource';
import cloneDeep from 'lodash/cloneDeep';
export default {
  name: 'Bd',
  components: {
    basicQuest,
    answerOption,
  },
  computed: {
    filterMap() {
      return getDataSource('editForm', 'questFilterMap');
    },
    tableMap() {
      return getDataSource('tableColumn', 'questTableMap');
    },
  },
  data() {
    return {
      optionListMap: {},
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 表格数据
      userList: [],
      // 下拉数据对象
      tableOptionMap: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {},
      // 表单参数
      basicForm: { specifiedRange: 0, matchSwitch: 0 },
      // 定向答题
      questionDirect: {},
      // 答题选项
      optionList: [],

      params: {
        basicForm: {},
        questionDirect: {},
        optionList: [],
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.$nextTick(() => {
        this.$refs.tableListContainer.init();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.$nextTick(() => {
        this.basicForm = this.$options.data().basicForm;
        this.questionDirect = this.$options.data().questionDirect;
        this.optionList = this.$options.data().optionList;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      const tableListContainer = this.$refs.tableListContainer;
      tableListContainer.pagination = tableListContainer.$options.data().pagination;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const filterContainer = this.$refs.filterContainer;
      filterContainer.resetForm('editFormData');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = '添加必答题';
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate({ id }) {
      getBd(id).then((res) => {
        this.title = '修改必答题';
        this.open = true;
        const data = res.data;
        Object.keys(data).map((key) => {
          const keyArr = ['themeIds'];
          const fieldArr = ['themeId'];
          if (['questionDirectResp', 'optionList'].includes(key)) {
            const dataMap = {
              questionDirectResp: 'questionDirect',
              optionList: 'optionList',
            };
            this[dataMap[key]] = data[key];
            this.params[dataMap[key]] = data[key];
          } else if (data[key] && keyArr.includes(key)) {
            const index = keyArr.findIndex((item) => item === key);
            const valueArr = data[key].split(',').map((item) => parseInt(item));
            this.$set(this.basicForm, fieldArr[index], valueArr);
            this.$set(this.params.basicForm, fieldArr[index], valueArr);
            this.$set(this.basicForm, key, data[key]);
            this.$set(this.params.basicForm, key, data[key]);
          } else {
            this.$set(this.basicForm, key, data[key]);
            this.$set(this.params.basicForm, key, data[key]);
          }
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? row.id : this.ids.join(',');
      this.$modal
        .confirm('是否确认删除Id编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBd(ids);
        })
        .then(() => {
          this.getList();
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const tableListContainer = this.$refs.tableListContainer;
      const pagination = tableListContainer.pagination;
      const params = {
        ...pagination,
        ...this.queryParams,
      };
      exportBd(params, '必答题数据导出');
    },
    changeAction(prop) {},
    /** 提交按钮 */
    submitForm() {
      let optionFlag = true;
      if (!this.params.optionList.length) return this.$message.error('答题选项不能为空');
      this.params.optionList.some((item, index) => {
        if (!item.optionTitle) {
          optionFlag = false;
          this.$message.error(`第${index + 1}行的选项名称不能为空`);
        }
      });
      if (!optionFlag) return;
      const basicQuest = this.$refs.basicQuest;
      const basicQuestContainer = basicQuest.$refs.basicQuestContainer;
      basicQuestContainer.$refs.editFormData.validate((basicValid) => {
        if (basicValid) {
          const { basicForm, questionDirect, optionList } = this.params;
          const params = cloneDeep({
            ...basicForm,
            questionDirect,
            optionList,
          });
          if (basicForm.id) {
            updateBd(params).then(() => {
              this.$message.success('修改成功');
              this.reset();
              this.getList();
              this.open = false;
            });
          } else {
            addBd(params).then(() => {
              this.$message.success('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
